package com.keepfriend;

import java.util.ArrayList;

import Database.MyDatabase;
import Utils.Common;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private static MyDatabase db;

    private ArrayAdapter<String> adapterListFriend;
    private ArrayList<String> arrListFriend;
    private ListView lstViewMain;

    private Dialog dialog = null;
    private Cursor cursor = null;

    private ListView lstPhoneBook = null;

    private static final int PICK_CONTACT = 3;

    private int friend_id_selected = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	db = new MyDatabase(this);
	lstViewMain = (ListView) findViewById(R.id.listFriend);
	// registerForContextMenu(lstViewMain);
	initTab();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	// Handle action bar item clicks here. The action bar will
	// automatically handle clicks on the Home/Up button, so long
	// as you specify a parent activity in AndroidManifest.xml.
	int id = item.getItemId();
	if (id == R.id.action_add_many) {
	    actionMenuAddFriendClick();
	    return true;
	} else if (id == R.id.action_add_one) {
	    actionAddOneClick();
	    return true;
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
	/*-AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
	int friend_id = Common.getIdFromText(arrListFriend.get(aInfo.position));*/

	switch (item.getItemId()) {
	case R.id.ctmi_ok:
	    ctmi_okClick(friend_id_selected);
	    break;
	case R.id.ctmi_cancel:
	    ctmi_cancelClick(friend_id_selected);
	    break;
	case R.id.ctmi_delete:
	    ctmi_deleteClick(friend_id_selected);
	    break;
	default:
	    break;
	}

	return super.onContextItemSelected(item);
    }

    @Override
    protected void onActivityResult(int reqCode, int resultCode, Intent data) {
	super.onActivityResult(reqCode, resultCode, data);

	switch (reqCode) {
	case (PICK_CONTACT):
	    if (resultCode == Activity.RESULT_OK) {
		Uri contactData = data.getData();
		Cursor c = managedQuery(contactData, null, null, null, null);

		if (c.moveToFirst()) {
		    // other data is available for the Contact. I have decided
		    // to only get the name of the Contact.
		    String friend_name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
		    String phone_id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
		    db.addFriend(friend_name, phone_id);
		    loadTabOops();
		}
	    }
	}
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	super.onCreateContextMenu(menu, v, menuInfo);
	getMenuInflater().inflate(R.menu.ctm_lstitem_main, menu);
    }

    /**************************************************************
     ** *** ** *** ** *** ** *** ** *** ** *** ** *** ** *** ** ***
     *************************************************************/
    private void initTab() {
	// 1.Lay tab host
	TabHost th = (TabHost) findViewById(R.id.tabhost);
	th.setup(); // phải chạy lệnh này trước khi add tab
	th.setOnTabChangedListener(new OnTabChangeListener() {
	    @Override
	    public void onTabChanged(String tabId) {
		if ("tabOops".equals(tabId)) {
		    loadTabOops();
		} else if ("tabGood".equals(tabId)) {
		    loadTabGood();
		} else if ("tabLookHere".equals(tabId)) {
		    loadTabLookHere();
		}
	    }
	});

	// 2.Tao tab spec
	TabHost.TabSpec spec;
	spec = th.newTabSpec("tabOops");
	spec.setContent(R.id.tab_oops);
	spec.setIndicator("1-Oops");
	th.addTab(spec);

	spec = th.newTabSpec("tabGood");
	spec.setContent(R.id.tab_good);
	spec.setIndicator("2-Good");
	th.addTab(spec);

	spec = th.newTabSpec("tabLookHere");
	spec.setContent(R.id.tab_look_here);
	spec.setIndicator("3-Look here");
	th.addTab(spec);

	th.setCurrentTab(0);
    }

    private void loadTabOops() {
	arrListFriend = db.getListFriend();
	adapterListFriend = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListFriend);
	lstViewMain.setAdapter(adapterListFriend);
	lstViewMain.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> adap, View v, int arg2, long arg3) {
		Log.i("click", "xxx");
		friend_id_selected = Common.getIdFromText(((TextView) v).getText().toString());
		registerForContextMenu(v);
		v.setLongClickable(false);
		adap.showContextMenuForChild(v);
	    }
	});
    }

    private void loadTabGood() {

    }

    private void loadTabLookHere() {

    }

    /**
     * 
     * @return
     */
    private Cursor getPhoneBook() {
	// @f:off
	String[] mProject = new String[] { 
			ContactsContract.Contacts._ID,
			Phone.CONTACT_ID, 
			ContactsContract.Contacts.DISPLAY_NAME,
			Phone.NUMBER };
			
	Cursor c = getContentResolver().query(
			Phone.CONTENT_URI, 
			mProject, 
			null, 
			null,
			"lower(" + Phone.DISPLAY_NAME + ")");
	// @f:on

	return c;
    }

    /**************************************************************
     ** SU KIEN CLICK*** ** *** ** *** ** *** ** *** ** *** ** ***
     *************************************************************/

    /**
     * Menu click
     */
    private void actionMenuAddFriendClick() {
	View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_friend, null);

	dialog = new Dialog(this);
	dialog.setContentView(dialogView);
	dialog.setCancelable(true);
	dialog.setTitle("Add");
	dialog.show();

	cursor = getPhoneBook();

	String[] from = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
	int[] to = new int[] { R.id.tvContactId, R.id.tvContactName };
	SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.listitem_phonebook, cursor, from, to);

	lstPhoneBook = (ListView) dialogView.findViewById(R.id.lstPhoneBook);
	lstPhoneBook.setAdapter(adapter);
	lstPhoneBook.setOnItemClickListener(new OnItemClickListener() {
	    @Override
	    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
		CheckBox cb = (CheckBox) view.findViewById(R.id.cbContact);
		cb.setChecked(cb.isChecked() ? false : true);
	    }
	});
    }

    private void actionAddOneClick() {
	Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
	startActivityForResult(intent, PICK_CONTACT);
    }

    /**
     * Dialog add friend/button OK click
     * 
     * @param v
     */
    public void btnOKClick(View v) {
	SparseBooleanArray checked = lstPhoneBook.getCheckedItemPositions();
	String friend_name = null;
	String phone_id = null;
	for (int i = 0; i < checked.size(); i++) {
	    cursor.moveToPosition(checked.keyAt(i));
	    friend_name = cursor.getString(2);
	    phone_id = cursor.getString(0);
	    db.addFriend(friend_name, phone_id);
	}

	loadTabOops();
	dialog.cancel();
	cursor.close();
    }

    /**
     * Dialog add friend >> button Cancel click
     * 
     * @param v
     */
    public void btnCancelClick(View v) {
	dialog.cancel();
	cursor.close();
    }

    private void ctmi_okClick(int friend_id) {
	if (friend_id_selected != -1) {
	    db.updateSeenFriend(friend_id);
	    loadTabOops();
	}
	friend_id_selected = -1;
    }

    private void ctmi_cancelClick(int friend_id) {
	friend_id_selected = -1;
    }

    private void ctmi_deleteClick(int friend_id) {
	if (friend_id_selected != -1) {
	    db.deleteFriend(friend_id);
	    loadTabOops();
	}
	friend_id_selected = -1;
    }

}
